package com.kfd.wx;


import com.kfd.bean.*;
import com.kfd.exception.DuplicateCodeException;
import com.kfd.exception.DuplicateNumberException;
import com.kfd.mvc.ResponseBody;
import com.kfd.mvc.ResponseView;
import com.kfd.service.EadminService;
import com.kfd.service.ExpressService;
import com.kfd.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class UserController {

    @ResponseBody("/wx/loginSms.do")
    public String loginSms(HttpServletRequest request,HttpServletResponse response){
        String phone = request.getParameter("phone");
        int code = RandomUtil.getCode();

        //发送短信
        boolean send = SendSms.send(phone, String.valueOf(code));
        //临时验证码测试用
//        boolean send=true;
//        code=123;

        Message message = new Message();
        if(send){
            //短信发送成功
            message.setStatus(0);
            message.setResult("验证码发送成功！");
        }else{
            message.setStatus(-1);
            message.setResult("验证码发送失败，请稍后再试！");
        }
        UserUtil.setLoginSms(request.getSession(),phone,code+"");
        return JSONUtil.toJSON(message);
    }

    /**
     * 用户登录方法，判断用户是快递员还是用户
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request,HttpServletResponse response){
        String code = request.getParameter("code");
        String phone = request.getParameter("phone");
        String phoneSms = UserUtil.getLoginSms(request.getSession(), code);
        Message message = new Message();
        Eadmin eadmin=null;
        if(phoneSms != null && phoneSms.equals(phone)){
            //查询该用户是否是快递员
            eadmin = EadminService.findByPhone(phoneSms, 1);
            if(eadmin != null){
                EadminService.updateLoginIpTime(eadmin.getUsername(),new Date(),request.getRemoteAddr());
                message.setStatus(0);
                message.setResult("登录成功!快递员："+eadmin.getUsername());
            }else{
                //查询该用户是否是普通用户
                eadmin = EadminService.findByPhone(phoneSms, 0);
                if(eadmin != null){
                    EadminService.updateLoginIpTime(eadmin.getUsername(),new Date(),request.getRemoteAddr());
                    message.setStatus(1);
                    message.setResult("登录成功!用户："+eadmin.getUsername());
                }else{
                    try {

                        boolean insert = EadminService.insert(new Eadmin(phoneSms, Timestamp.valueOf(DateFormatUtil.format(new Date())),request.getRemoteAddr(),phoneSms), 0);
                        if(insert){
                            message.setStatus(2);
                            message.setResult("注册成功!请尽快完善用户信息");
                        }else{
                            message.setStatus(3);
                            message.setResult("注册失败!");
                        }

                    } catch (DuplicateCodeException e) {
                        e.printStackTrace();
                    } catch (DuplicateNumberException e) {
                        e.printStackTrace();
                    }
                }
            }
            UserUtil.setWxUser(request.getSession(),phoneSms);
            UserUtil.setWxUsermsg(request.getSession(),eadmin);
        }else{
            message.setStatus(3);
            message.setResult("验证码错误或手机号与验证码不匹配!");
        }
        return JSONUtil.toJSON(message);
    }

    /**
     * 用户退出登录
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        //销毁用户信息
        request.getSession().invalidate();
        Message message = new Message(0);
        return JSONUtil.toJSON(message);
    }
    @ResponseBody("/wx/UserInfo.do")
    public String UserInfo(HttpServletRequest request,HttpServletResponse response){
        String wxUser = UserUtil.getWxUser(request.getSession());
        Eadmin byPhone = EadminService.findByPhone(wxUser, 1);
        Message message = new Message();
        if(byPhone != null){
            message.setStatus(0);
        }else{
            message.setStatus(1);
        }
        message.setResult(wxUser);
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/findExpressList.do")
    public String findExpressList(HttpServletRequest request,HttpServletResponse response){
        String wxUser = UserUtil.getWxUser(request.getSession());
        //获取用户未取件的快递
        List<Express> list0 = ExpressService.findByUserPhone(wxUser, 0);
        List<BootstrapTableExpress> byUserPhone0 = new ArrayList<>();

        if(list0 != null){
            for (Express express : list0) {
                BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),express.getUsername(),express.getUserphone(),express.getCompany(),(express.getCode() == null || express.getCode().equals(""))?"已取件":express.getCode(),String.valueOf(express.getIntime()),String.valueOf(express.getOuttime() == null?"未出库":express.getOuttime()),String.valueOf(express.getStatus() == 0?"待取件":"已取件"),express.getSysPhone());
                byUserPhone0.add(bootstrapTableExpress);
            }
        }


        //获取用户已取件的快递
        List<Express> list1 = ExpressService.findByUserPhone(wxUser, 1);
        List<BootstrapTableExpress> byUserPhone1 = new ArrayList<>();
        if(list1 != null){
            for (Express express : list1) {
                BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),express.getUsername(),express.getUserphone(),express.getCompany(),(express.getCode() == null || express.getCode().equals(""))?"已取件":express.getCode(),String.valueOf(express.getIntime()),String.valueOf(express.getOuttime() == null?"未出库":express.getOuttime()),String.valueOf(express.getStatus() == 0?"待取件":"已取件"),express.getSysPhone());
                byUserPhone1.add(bootstrapTableExpress);
            }
        }

        Message message = new Message();

        //分支：用户同时有已取件和未取件
        if(byUserPhone0.size() != 0 && byUserPhone1.size() != 0){
            //用户有消息
            message.setStatus(0);

            //内存地址指向同一个对象，导致已取件也跟随更改
            List<BootstrapTableExpress> byUserPhoneTest = new ArrayList<>();
            for (BootstrapTableExpress bootstrapTableExpress : byUserPhone1) {
                try {
                    byUserPhoneTest.add(bootstrapTableExpress.clone());
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
            for (BootstrapTableExpress express : byUserPhoneTest) {
                express.setStatus("待取件");
            }
            byUserPhone0.addAll(byUserPhoneTest);
            byUserPhone0.stream().sorted(((o1, o2) -> {
                long time = DateFormatUtil.ToTime(o1.getIntime());
                long time1 = DateFormatUtil.ToTime(o2.getIntime());
                return (int) (time-time1);
            }));
            byUserPhone0.addAll(byUserPhone1);
            byUserPhone0.stream().sorted(((o1, o2) -> {
                long time=DateFormatUtil.ToTime(o1.getIntime());
//                待取件":"已取件
                if("已取件".equals(o1.getStatus())){
                    time = DateFormatUtil.ToTime(o1.getOuttime());
                }
                long time1 = DateFormatUtil.ToTime(o2.getIntime());
                if("已取件".equals(o2.getStatus())){
                    time1 = DateFormatUtil.ToTime(o2.getOuttime());
                }
                return (int) (time-time1);
            }));
            message.setData(byUserPhone0);
            return JSONUtil.toJSON(message);
        }else{
            //用户只有未取件
            if(byUserPhone0.size() != 0){
                //用户有消息
                message.setStatus(0);

                byUserPhone0.stream().sorted(((o1, o2) -> {
                    long time = DateFormatUtil.ToTime(o1.getIntime());
                    long time1 = DateFormatUtil.ToTime(o2.getIntime());
                    return (int) (time-time1);
                }));

                message.setData(byUserPhone0);
                return JSONUtil.toJSON(message);
            }
            //用户只有已取件
            if(byUserPhone1.size() != 0){
                //用户有消息
                message.setStatus(0);

                List<BootstrapTableExpress> byUserPhoneTest = new ArrayList<>();
                for (BootstrapTableExpress bootstrapTableExpress : byUserPhone1) {
                    try {
                        byUserPhoneTest.add(bootstrapTableExpress.clone());
                    } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
                    }
                }
                for (BootstrapTableExpress express : byUserPhoneTest) {
                    express.setStatus("待取件");
                }
                byUserPhone1.addAll(byUserPhoneTest);
                byUserPhone1.stream().sorted(((o1, o2) -> {
                    long time=DateFormatUtil.ToTime(o1.getIntime());;
                    if("已取件".equals(o1.getStatus())){
                        time = DateFormatUtil.ToTime(o1.getOuttime());
                    }
                    long time1 = DateFormatUtil.ToTime(o2.getIntime());
                    if("已取件".equals(o2.getStatus())){
                        time1 = DateFormatUtil.ToTime(o2.getOuttime());
                    }
                    return (int) (time-time1);
                }));
                message.setData(byUserPhone0);
                return JSONUtil.toJSON(message);
            }
            //用户没有消息
            message.setStatus(-1);
            return JSONUtil.toJSON(message);
        }

    }
    @ResponseView("/wx/createQrcode.do")
    public String createQrcode(HttpServletRequest request,HttpServletResponse response){
        String code = request.getParameter("code");
        String type = request.getParameter("type");
        String userPhone=null;
        String qRCode=null;
        if("express".equals(type)){
            //快递二维码
            qRCode="express_"+code;
        }else{
            //用户所有快递
            userPhone=UserUtil.getWxUser(request.getSession());
            qRCode="userPhone_"+userPhone;
        }
        HttpSession session = request.getSession();
        session.setAttribute("qRCode",qRCode);
        return "/personQRcode.html";
    }

    @ResponseBody("/wx/getQrcode.do")
    public String getQRcode(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();
        String qRCode = (String) session.getAttribute("qRCode");
        Message message = new Message();

        if(qRCode == null){
            message.setStatus(-1);
            message.setResult("二维码获取失败，请稍后重试");
        }else{
            message.setStatus(0);
            message.setResult("获取成功");
            message.setResult(qRCode);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/userExpressList.do")
    public String userExpressList(HttpServletRequest request,HttpServletResponse response){
        String userphone = request.getParameter("userphone");
        List<Express> byUserPhone = ExpressService.findByUserPhone(userphone, 0);
        List<BootstrapTableExpress> byUserPhone1 = new ArrayList<>();
        if(byUserPhone != null){
            for (Express express : byUserPhone) {
                BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(express.getId(),express.getNumber(),express.getUsername(),express.getUserphone(),express.getCompany(),(express.getCode() == null || express.getCode().equals(""))?"已取件":express.getCode(),String.valueOf(express.getIntime()),String.valueOf(express.getOuttime() == null?"未出库":express.getOuttime()),String.valueOf(express.getStatus() == 0?"待取件":"已取件"),express.getSysPhone());
                byUserPhone1.add(bootstrapTableExpress);
            }
        }

        Message message = new Message();
        if(byUserPhone == null){
            message.setStatus(-1);
            message.setResult("该用户暂无快递");
        }else{
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(byUserPhone1);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/updateStatus.do")
    public String updateStatus(HttpServletRequest request,HttpServletResponse response){
        String code = request.getParameter("code");
        boolean b = ExpressService.updateStatus(code);
        Message message = new Message();
        if(b){
            message.setStatus(0);
            message.setResult("取件成功");
        }else{
            message.setStatus(-1);
            message.setResult("取件失败,请用户更新二维码重试！");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/findBycode.do")
    public String findBycode(HttpServletRequest request,HttpServletResponse response){
        String code = request.getParameter("code");
        Express e = ExpressService.findByCode(code);


        Message message = new Message();
        if(e != null){
            BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),e.getCode(),
                    String.valueOf(e.getIntime()),String.valueOf(e.getOuttime()),e.getStatus()+"",e.getSysPhone());
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(bootstrapTableExpress);
        }else{
            message.setStatus(-1);
            message.setResult("查询失败");
        }
        return  JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/findUser.do")
    public String findUser(HttpServletRequest request,HttpServletResponse response){
            String wxUser = UserUtil.getWxUser(request.getSession());
        Eadmin byPhone = EadminService.findByPhone(wxUser, 1);
        if(byPhone == null){
            byPhone = EadminService.findByPhone(wxUser, 0);
        }
        Message message = new Message();
        if(byPhone.getName()==null||byPhone.getPassword()==null){
            //都没完善
            message.setStatus(-1);
        }else{
            //完善了
            message.setStatus(0);
            UserUtil.setWxUsermsg(request.getSession(),byPhone);
        }
        message.setData(byPhone);
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/indexQueryExpress.do")
    public String indexQueryExpress(HttpServletRequest request,HttpServletResponse response){
        String expressNum = request.getParameter("expressNum");
        Express e = ExpressService.findByNumber(expressNum);
        Message message = new Message();
        if(e != null){
            BootstrapTableExpress bootstrapTableExpress = new BootstrapTableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),e.getCode(),
                    String.valueOf(e.getIntime()),String.valueOf(e.getOuttime()),e.getStatus()+"",e.getSysPhone());
            message.setStatus(0);

            message.setResult("查询成功:"+(e.getStatus()==1?"快件已取出":"快件未取出"));
            message.setData(bootstrapTableExpress);
        }else{
            message.setStatus(-1);
            message.setResult("查询失败,快件不存在");
        }
        return  JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/newUpdateUser.do")
    public String newUpdateUser(HttpServletRequest request,HttpServletResponse response){
        String code = request.getParameter("msg");
        String phone = request.getParameter("phone");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String phoneSms = UserUtil.getLoginSms(request.getSession(), code);
        Message message = new Message();
        if(phoneSms != null && phoneSms.equals(phone)){
            //查询该用户是否是快递员
            Eadmin byPhone = EadminService.findByPhone(phoneSms, 1);
            if(byPhone != null){
                byPhone.setName(name);
                byPhone.setPassword(password);
                boolean update = EadminService.update(byPhone);
                if(update){
                    message.setStatus(0);
                    message.setResult("修改成功!");
                }else{
                    message.setStatus(-1);
                    message.setResult("修改失败!");
                }

            }else{
                //查询该用户是否是普通用户
                Eadmin byUser = EadminService.findByPhone(phoneSms, 0);

                    byUser.setName(name);
                    byUser.setPassword(password);
                    boolean update = EadminService.update(byUser);
                    if(update){
                        message.setStatus(0);
                        message.setResult("修改成功!");
                    }else{
                        message.setStatus(-1);
                        message.setResult("修改失败!");
                    }
            }
            UserUtil.setWxUser(request.getSession(),phoneSms);
        }else{
            message.setStatus(3);
            message.setResult("验证码错误");
        }
        return JSONUtil.toJSON(message);
    }



    @ResponseBody("/wx/newUpUser.do")
    public String newUpUser(HttpServletRequest request,HttpServletResponse response){
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        String phoneSms = UserUtil.getNewLoginSms(request.getSession(), code);
        Eadmin wxUsermsg = UserUtil.getWxUsermsg(request.getSession());
        Message message = new Message();
        if(phoneSms != null && phoneSms.equals(phone)){
            //查询该用户是否是快递员
            Eadmin byPhone = EadminService.findByPhone(wxUsermsg.getUserPhone(), 1);
            if(byPhone != null){

                byPhone.setName(name);
                byPhone.setUserPhone(phone);
                boolean update = EadminService.update(byPhone);
                if(update){
                    message.setStatus(0);
                    message.setResult("用户信息更新成功!");
                }else{
                    message.setStatus(-1);
                    message.setResult("用户信息更新失败，请联系管理员!");
                }
            }else {
                //查询该用户是否是普通用户
                Eadmin byUser = EadminService.findByPhone(wxUsermsg.getUserPhone(), 0);
                if (byUser != null) {

                    byUser.setName(name);
                    byUser.setUserPhone(phone);
                    boolean update = EadminService.update(byUser);
                    if (update) {
                        message.setStatus(0);
                        message.setResult("用户信息更新成功!");
                    } else {
                        message.setStatus(-1);
                        message.setResult("用户信息更新失败，请联系管理员!");
                    }
                }
            }
            UserUtil.setWxUser(request.getSession(), phoneSms);
        }else{
            message.setStatus(-1);
            message.setResult("验证码错误或手机号与验证码不匹配!");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/loginSmsend.do")
    public String loginSmsend(HttpServletRequest request,HttpServletResponse response){
        String phone = request.getParameter("phone");
        int code = RandomUtil.getCode();

        //发送短信
        boolean send = SendSms.send(phone, String.valueOf(code));
        //临时验证码测试用
//        boolean send=true;
//        code=321;

        Message message = new Message();
        if(send){
            //短信发送成功
            message.setStatus(0);
            message.setResult("验证码发送成功！");
        }else{
            message.setStatus(-1);
            message.setResult("验证码发送失败，请稍后再试！");
        }
        UserUtil.setNewLoginSms(request.getSession(),phone,code+"");
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/lanren.do")
    public String lanren(HttpServletRequest request,HttpServletResponse response){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        List [] data = new List[3];
        List<lanren> sum = ExpressService.getLanlist(null, null);
        List<lanren> yearUp = ExpressService.getLanlist(year+"", null);
        List<lanren> menthUp = ExpressService.getLanlist(year+"", month+"");
        data[0] = sum;
        data[1] = yearUp;
        data[2] =menthUp;
        return JSONUtil.toJSON(data);
    }

    @ResponseBody("/wx/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("username");
        String userPhone = request.getParameter("userPhone");

        boolean insert = ExpressService.insert(new Express(number, username, userPhone, company, UserUtil.getWxUser(request.getSession())),0);

        Message message = new Message();

        if(insert){
            message.setStatus(0);
        }else{
            message.setStatus(-1);
        }
        return JSONUtil.toJSON(message);
    }
}
